package handler

import (
	"context"

	"gitee.com/chunanyong/zorm"
	"gitee.com/workits/workits-admin/internal/app/system/entity"
	"gitee.com/workits/workits-admin/internal/app/system/model"
	"github.com/pkg/errors"
)

var SettingsHandler = new(settingsHandler)

type settingsHandler struct {
}

// Config 获取系统所有有效配置
//
//	@Summary	获取系统所有有效配置
//	@Tags		system
//	@Produce	json
//	@Success	200	{object}	ginx.RespWrapper{data=model.SettingsConfigRespModel}
//	@Router		/system/settings/config [post]
func (h *settingsHandler) Config(ctx context.Context) (*model.SettingsConfigRespModel, error) {
	// 构造查询条件
	finder := zorm.NewSelectFinder(entity.SysSettingsTableName)
	finder.Append("where deleted_at is null")
	finder.Append("and disabled = ?", "N")
	finder.SelectTotalCount = false

	// 执行查询
	var items []entity.SysSettingsEntity
	if err := zorm.Query(ctx, finder, &items, nil); err != nil {
		return nil, errors.WithStack(err)
	}

	// 数据转换
	ret := &model.SettingsConfigRespModel{}
	for _, item := range items {
		switch item.Key {
		case "sysName":
			ret.SysName = item.Value
		case "logo":
			ret.Logo = item.Value
		case "icon":
			ret.Icon = item.Value
		case "loginBanner":
			ret.LoginBanner = item.Value
		case "iconType":
			ret.IconType = item.Value
		case "primaryColor":
			ret.PrimaryColor = item.Value
		case "enableWatermark":
			ret.EnableWatermark = item.Value
		case "copyrightYear":
			ret.CopyrightYear = item.Value
		case "copyrightName":
			ret.CopyrightName = item.Value
		case "copyrightLink":
			ret.CopyrightLink = item.Value
		case "icp":
			ret.ICP = item.Value
		}
	}

	return ret, nil
}

// Privacy 获取系统所有有效配置
//
//	@Summary	获取系统所有有效配置
//	@Tags		system
//	@Produce	json
//	@Param		body	body		model.SettingsPrivacyReqModel	true	"个人隐私策略参数"
//	@Success	200	{object}	ginx.RespWrapper{data=model.SettingsPrivacyRespModel}
//	@Router		/system/settings/privacy [post]
func (h *settingsHandler) Privacy(ctx context.Context, reqModel *model.SettingsPrivacyReqModel) (*model.SettingsPrivacyRespModel, error) {
	// 构建查询条件
	finder := zorm.NewSelectFinder(entity.SysPrivacyTableName)
	finder.Append("where deleted_at is null")
	finder.Append("and pub_status = ?", "Y")
	if len(reqModel.Version) == 0 {
		finder.Append("order by ver_idx desc")
	} else {
		finder.Append("and version = ?", reqModel.Version)
	}

	// 执行查询详情
	var item entity.SysPrivacyEntity
	if _, err := zorm.QueryRow(ctx, finder, &item); err != nil {
		return nil, err
	}

	// 构造返回值
	ret := &model.SettingsPrivacyRespModel{
		Version: item.Version,
		Content: item.Content,
		PubTime: item.PubTime,
	}

	// 构造查询个人隐私策略列表条件
	finder = zorm.NewSelectFinder(entity.SysPrivacyTableName, "version")
	finder.Append("where deleted_at is null")
	finder.Append("and pub_status = ?", "Y")
	finder.Append("order by ver_idx desc")
	finder.SelectTotalCount = false
	var history []string
	if err := zorm.Query(ctx, finder, &history, nil); err != nil {
		return nil, err
	}
	ret.History = history

	return ret, nil
}
